package connection;

import commonUtil.CommonConst;

import java.sql.*;

/**
 * Created by xiezy3 on 2016/8/9.
 */
public class JdbcConnection {
    public static final String url = CommonConst.JdbcConn.URL;
    public static final String name = CommonConst.JdbcConn.DRIVER_NAME;
    public static final String user = CommonConst.JdbcConn.USER_NAME;
    public static final String password = CommonConst.JdbcConn.PASSWORD;

    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(name); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //用于关闭JDBC打开的ResultSet、Connection、PreparedStatement
    public void close(ResultSet rs,Connection conn ,PreparedStatement stmt) {
        try {
            if(rs !=null)
                rs.close();
        } catch (SQLException e) {
            System.out.println("Close ResultSet failed!");
            e.printStackTrace();
        }finally {
            try {
                if(conn != null)
                    conn.close();
            } catch (SQLException e) {
                System.out.println("Close Connection failed!");
                e.printStackTrace();
            }finally{
                try {
                    if(stmt != null)
                        stmt.close();
                } catch (SQLException e) {
                    System.out.println("Close Statement failed!");
                    e.printStackTrace();
                }
            }
        }
    }
}
